package com.grm.common.exception;

import com.grm.common.entity.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result errorHandler(HttpServletRequest req, Exception e) {
        String errorMessage = "未知异常：" + e.getMessage();
        log.error("未知异常",e);
        return Result.failed(errorMessage);
    }

    @ExceptionHandler(BusinessException.class)
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        BusinessException businessException = (BusinessException)e;
        String errorMessage = businessException.getMessage();
        log.error("业务异常：{}",e.getMessage());
        return Result.failed(businessException.getCode(), errorMessage);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringJoiner sj = new StringJoiner(";");
        e.getBindingResult().getFieldErrors().forEach(x -> sj.add(x.getField() + ":" + x.getDefaultMessage()));
        String errorMessage = sj.toString();
        log.error(errorMessage);
        return Result.failed(errorMessage);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        String errorMessage = "请求体不能为空!";
        log.error(errorMessage);
        return Result.failed(errorMessage);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
        String errorMessage = "请求参数: " + e.getParameterName() + "不能为空!";
        log.error(errorMessage);
        return Result.failed(errorMessage);
    }
}
